/**
 * 工具方法
 * @author ytl
 */
import {CLIENT_WECHAT, CLIENT_ALIPAY} from 'components/api/interface-hhy';
import {orderPayNotify} from 'components/api/interface-saas-order';
import {Toast} from 'mint-ui';

/**
 * 判断是微信内置浏览器
 * @author ytl
 * @return {boolean}
 */
export function isWechat() {
  let userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.match(/MicroMessenger/i)) {
    return true;
  }
  return false;
}

/**
 * 判断是支付宝内置浏览器
 * @author ytl
 * @return {boolean}
 */
export function isAlipay() {
  let userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.match(/Alipay/i)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 获取客户端类型
 * @author ytl
 * @return {*}
 */
export function getClientType() {
  if (isWechat()) {
    return CLIENT_WECHAT;
  } else if (isAlipay()) {
    return CLIENT_ALIPAY;
  }
  return '';
}

/**
 * 存储sessionStorageItem
 * @todo 应用调试完成后应考虑加密算法
 * @author ytl
 * @param key string
 * @param value Object|Array|String
 */
export function setSessionStorageItem(key, value) {
  let item = '';
  if (value instanceof Object) {
    item = JSON.stringify(value);
  } else {
    item = value;
  }
  window.sessionStorage.setItem(key, item);
}

/**
 * 获取sessionStorageItem @todo 应用调试完成后应考虑解密算法
 * @author ytl
 * @param key string
 * @return {null}|string|Object
 */
export function getSessionStorageItem(key) {
  let value = window.sessionStorage.getItem(key);
  if (!value) {
    return null;
  }
  try {
    return JSON.parse(value);
  } catch (err) {
    return value;
  }
}
// 搜索功能使用
// 过滤菜品名称
export function filterJson(goodsList, searchTxt) {
  let filterFoods = [];
  let filterGoods = [];
  if (goodsList !== null && goodsList.length > 0) {
    goodsList.forEach((good) => {
      if (good.foodList !== null && good.foodList.length > 0) {
        filterFoods = [];
        let temp = good.foodList.findIndex((item) => { // 查找匹配的商品
          return item.name.indexOf(searchTxt) >= 0;
        });
        if (temp === -1) {
          // good.foodList.splice(temp, 1);
        } else {
          let currentFood = good.foodList[temp];
          filterFoods.push(currentFood);
        }
      }
      let newGood = '{"classId":' + good.classId + ',"className":' + '"' + good.className + '"' + ',"foodList":' + JSON.stringify(filterFoods) + ',"sort":' + good.sort +
        '}';
      filterGoods.push(newGood);
    });
  } else {
    return null;
  }
  return arrayToJson(filterGoods) === 'undefined' ? null : arrayToJson(filterGoods);
}
// 获取浏览器地址栏中的参数
export function getParameter(name) {
  let value = location.search.match(new RegExp('[?&]' + name + '=([^&]*)(&?)', 'i'));
  return value ? decodeURIComponent(value[1]) : '';
}
export function arrayToJson(o) {
  let r = [];
  if (typeof o === 'string') return o.replace(/([\'\"\\])/g, '$1').replace(/(\n)/g, '').replace(/(\r)/g, '\\r').replace(/(\t)/g, '\\t');
  if (typeof o === 'object') {
    if (!o.sort) {
      for (let i in o) {
        r.push(i + ':' + arrayToJson(o[i]));
      }
      if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
        r.push('toString:' + o.toString.toString());
      }
      r = '{' + r.join() + '}';
    } else {
      for (let i = 0; i < o.length; i++) {
        r.push(arrayToJson(o[i]));
      }
      r = '[' + r.join() + ']';
    }
    return r;
  }
  return o.toString();
}

/**
 * 存储localStorageItem @todo 应用调试完成后应考虑加密算法
 * @author ytl
 * @param key string
 * @param value Object|Array|String
 * @param dueTime int 本地存储的期限（秒），0表示永久有效
 */
export function setLocalStorageItem(key, value, dueTime = 0) {
  let expireTime = 0;
  if (dueTime > 0) {
    expireTime = new Date().getTime() + dueTime;
  }

  let item = JSON.stringify({data: value, expireTime: expireTime});
  window.localStorage.setItem(key, item);
}

/**
 * 获取sessionStorageItem @todo 应用调试完成后应考虑解密算法
 * @author ytl
 * @param key string
 * @return {null}|string|Object
 */
export function getLocalStorageItem(key) {
  let value = window.localStorage.getItem(key);
  if (!value) {
    return null;
  }
  value = JSON.parse(value);
  let curTime = new Date().getTime();
  if (value.expireTime && value.expireTime > 0 && value.expireTime < curTime) {
    return null;
  }
  return value.data;
}

/**
 * 格式化秒数
 * @author ytl
 * @param leftTime 开始的秒数
 * @return {Object}
 */
export function formatTime(leftTime) {
  let dd = parseInt(leftTime / 60 / 60 / 24, 10);  // 剩余天数
  let hh = parseInt(leftTime / 60 / 60 % 24, 10);  // 剩余小时数
  let mm = parseInt(leftTime / 60 % 60, 10); // 剩余分钟数
  let ss = parseInt(leftTime % 60, 10);  // 剩余秒数
  dd = checkTime(dd);
  hh = checkTime(hh);
  mm = checkTime(mm);
  ss = checkTime(ss);
  return {
    dd: dd,
    mm: mm,
    hh: hh,
    ss: ss
  };
}

/**
 * 不满两位前面补零
 * @param time 时间值
 * @return {*}
 */
function checkTime(time) {
  if (time < 10) {
    time = '0' + time;
  }
  return time;
}

/**
 * 微信支付入口
 * @param {Object} payInfo
 * @param {Object} vm vue实例
 * @param {Function} callBack
 */
export function wechatCallpay(payInfo, vm, callBack) {
  if (typeof WeixinJSBridge === undefined) {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', wechatJsApiCall(payInfo, vm, callBack), false);
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', wechatJsApiCall(payInfo, vm, callBack));
      document.attachEvent('onWeixinJSBridgeReady', wechatJsApiCall(payInfo, vm, callBack));
    }
  } else {
    wechatJsApiCall(payInfo, vm, callBack);
  }
}

/**
 * 调用微信JS api 收银台
 * @param {Object} payInfo
 * @param {Object} vm vue实例
 * @param {Function} callBack
 * @todo Toast
 */
export function wechatJsApiCall(payInfo, vm, callBack) {
  WeixinJSBridge.invoke('getBrandWCPayRequest', payInfo, function (res) {
    // alert(JSON.stringify(payInfo));
    // alert(res.err_msg);
    // alert(res.err_code + res.err_desc + res.err_msg);
    if (res.err_msg === 'get_brand_wcpay_request:ok') {
      payInfo.out_trade_no && orderPayNotify(payInfo.out_trade_no);
      callBack && callBack(vm);
    }
    if (res.err_msg === 'get_brand_wcpay_request:cancel') {
      Toast('支付取消了');
    }
    if (res.err_msg === 'get_brand_wcpay_request:fail') {
      Toast('支付失败了');
    }
  });
}

/**
 * 由于js的载入是异步的，所以可以通过该方法，当AlipayJSBridgeReady事件发生后，再执行callback方法
 * @param {Function} callback
 */
export function alipayReady(callback) {
  if (window.AlipayJSBridge) {
    callback && callback();
  } else {
    document.addEventListener('AlipayJSBridgeReady', callback, false);
  }
}

/**
 * 阿里支付入口 唤起alipay js api 收银台
 * @param {Object} payInfo
 * @param {Object} vm vue实例
 * @param {Function} callback
 */
export function alipayCallpay(payInfo, vm, afterJsPay) {
  alipayReady(function () {
    AlipayJSBridge.call('tradePay', {
      tradeNO: payInfo.trade_no
    }, function (data) {
      if (parseInt(data.resultCode) === 9000) {
        payInfo.out_trade_no && orderPayNotify(payInfo.out_trade_no);
        afterJsPay && afterJsPay(vm);
      } else {
        alert('支付失败了');
      }
    });
  });
}

/**
 * http请求错误码描述
 * @param {Object} err 请求错误对象
 * @return {Object} err
 */
export function httpErrorMessage(err) {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '请求错误';
        break;
      case 401:
        err.message = '未授权，请登录';
        break
      case 403:
        err.message = '拒绝访问';
        break;
      case 404:
        err.message = ``;
        break
      case 408:
        err.message = '请求超时';
        break;
      case 500:
        err.message = '服务器内部错误';
        break;
      case 501:
        err.message = '服务未实现';
        break;
      case 502:
        err.message = '网关错误';
        break;
      case 503:
        err.message = '服务不可用';
        break;

      case 504:
        err.message = '网关超时'
        break
      case 505:
        err.message = 'HTTP版本不受支持';
        break;
      default:
        err.message = '';
    }
  }

  return err;
}

/**
 * 检查某个元素是否有某个class
 * @param ele
 * @param className
 * @return {Boolean}
 */
export function hasClass(ele, className) {
  return ele && ele.className && ele.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}

/**
 * 给元素添加class
 * @param ele
 * @param className
 */
export function addClass(ele, className) {
  if (!hasClass(ele, className)) {
    ele.className += ' ' + className;
  };
}

/**
 * 元素移除class
 * @param ele
 * @param className
 */
export function removeClass(ele, className) {
  if (hasClass(ele, className)) {
    let reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
    ele.className = ele.className.replace(reg, ' ');
  }
}

/**
 * 元素toggle class
 * @param ele
 * @param className
 */
export function toggleClass(ele, className) {
  if (hasClass(ele, className)) {
    removeClass(ele, className);
  } else {
    addClass(ele, className);
  }
}

/**
 *
 * @param orderId
 */
export function redirectPayUrl (orderId) {
  let { href, protocol, host, search, hash, pathname } = window.location;
  // search = search || '?';
  let newHref = `${protocol}//${host}${pathname}${search}` + '#/pay/' + orderId;
  window.location.href = newHref;
}
/**
 *  格式化时间戳，转换为'yyyy-MM-dd hh:mm:ss'
 * @param timestamp
 */
export function formatTimestamp(timestamp) {
  let date = '';
  if (timestamp) {
    date = new Date(parseInt(timestamp) * 1000);
  } else {
    date = new Date();
  }
  let Y = date.getFullYear(),
    m = date.getMonth() + 1,
    d = date.getDate(),
    H = date.getHours(),
    i = date.getMinutes(),
    s = date.getSeconds();
  if (m < 10) {
    m = '0' + m;
  }
  if (d < 10) {
    d = '0' + d;
  }
  if (H < 10) {
    H = '0' + H;
  }
  if (i < 10) {
    i = '0' + i;
  }
  if (s < 10) {
    s = '0' + s;
  }
  let tt = Y + '-' + m + '-' + d + ' ' + H + ':' + i;
  return tt;
}
